package com.ruoyi.asset.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.io.IOUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具
 */
public class QrUtil {

    /**
     * 响应二维码
     * @param qrFile
     * @param response
     */
    public static void writeQr(String qrFile, HttpServletResponse response){
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setContentType("image/png");
            response.setHeader("Cache-Control", "no-cache");
            IOUtils.copy(new FileInputStream(qrFile), servletOutputStream);
            servletOutputStream.flush();
            servletOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 生成指定资产的二维码
     * @param url 内容
     * @param qrPath 路径
     * @param size 尺寸
     * @return
     */
    public static void genQr(String url, String qrPath, Integer size){
        File qrFile = new File(qrPath);
        try {
            // 准备一个Map集合，用来存放二维码的属性
            Map map = new HashMap();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            map.put(EncodeHintType.MARGIN, 1);

            // 获取文本内容

            // 创建zxing核心对象
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, size, size, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();

            // 生成二维码
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            // 响应
            FileOutputStream out = new FileOutputStream(qrFile);
            ImageIO.write(bufferedImage, "png",out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
